import React from 'react';
import moment from 'moment';
import { message } from 'antd';
import { getRecruitmentInfo, getRecruitmentInfoByEncryptId, acceptRecruitmentByEncryptId } from '@/services/user';

const isExpire = (startTime, offerEffectiveValue = 48) => {
    const endTime = moment(startTime).add(offerEffectiveValue, 'hour');
    const hours = moment().diff(endTime, 'seconds');
    // 测试失效时间 > 0 过期 <0 没过期
    if (hours > 0) {
        return true;
    }
    return false;
};

/**
 * 接受录用公用的处理逻辑
 */
export default function useHireConfirm({
    setOfferEffectiveValue,
    employId,
    setStatus,
    setCompanyName,
    agree,
    isDetailPage
}) {
    const [loadingData, setLoadingData] = React.useState(false);
    const [infoData, setInfoData] = React.useState({});
    const [submitLoading, setSubmitLoading] = React.useState(false);

    const getInfoData = async () => {
        setLoadingData(true);
        const service = isDetailPage ? getRecruitmentInfo : getRecruitmentInfoByEncryptId;
        const res = await service({ employId });
        setLoadingData(false);
        if (res.code === 10000) {
            // 招聘录用需求状态 recruitStatus（1=待处理 2=需协商 3=审批中 4=审批拒绝 5=审批撤回 6=待接收  7=已接受 8=已取消 9=已入职 10已淘汰 99=其他）
            const { recruitStatus: status, sendTime, offerEffectiveValue, companyName } = res.data;
            if (Number(status) === 7 || Number(status) === 9) {
                setStatus('accept');
            } else if (Number(status) === 8) {
                setStatus('reject');
            } else if (isExpire(sendTime, offerEffectiveValue)) {
                if (setOfferEffectiveValue) {
                    setOfferEffectiveValue(offerEffectiveValue);
                }
                setStatus('expire');
            }
            setCompanyName(companyName);
            setInfoData(res.data);
        } else {
            console.error(res.msg);
        }
    };

    const handleAccept = async () => {
        if (!agree) {
            return message.warning('请先确认接受录用并同意在入职前提供背调联系信息，接受背调');
        }
        setSubmitLoading(true);
        // 接受录用 employState 7
        const res = await acceptRecruitmentByEncryptId({ employId, employState: 7 });
        setSubmitLoading(false);
        if (res.code === 10000) {
            setStatus('accept');
        } else {
            message.error(res.msg);
        }
        return null;
    };
    const handleReject = () => {
        setStatus('confirmReject');
    };

    React.useEffect(() => {
        getInfoData();
        return () => {
            setInfoData({});
        };
    }, []);

    return { infoData, loadingData, handleAccept, handleReject, submitLoading };
}
